﻿
namespace Behemoth.Xml.Linq {

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml;
    using System.Xml.Linq;

    public static class Extensions {

        public static XElement GetXElement(this XmlNode node) {
            return GetXElement(node, XElementCreationMethod.UseWriter);
        }
        public static XElement GetXElement(this XmlNode node, XElementCreationMethod method) {
            if (node == null)
                return null;
            switch (method) {
                case XElementCreationMethod.UseWriter:
                    XDocument xDoc = new XDocument();
                    using (XmlWriter xmlWriter = xDoc.CreateWriter())
                        node.WriteTo(xmlWriter);
                    return xDoc.Root;
                case XElementCreationMethod.UseParser:
                    return XElement.Parse(node.OuterXml);
                case XElementCreationMethod.UseConstructor:
                    return new XElement(node.Name, node.InnerXml);
                default:
                    return null;
            }
        }

        public static XmlNode GetXmlNode(this XElement element) {
            if (element == null)
                return null;
            using (XmlReader xmlReader = element.CreateReader()) {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlReader);
                return xmlDoc;
            }
        }

        /// <summary>
        /// Returns a generic list of all elements where Name.LocalName matches the value provided.
        /// </summary>
        /// <param name="xe"></param>
        /// <param name="elementName"></param>
        /// <returns></returns>
        public static List<XElement> GetAllElementsOfType(this XElement xe, string elementName) {
            if (xe == null)
                return null;
            List<XElement> ctList = (from XElement ct in xe.DescendantsAndSelf()
                where ct.Name.LocalName.Equals(elementName, StringComparison.InvariantCulture)
                select ct).ToList();
            return (List<XElement>)ctList;
        }

    }

    /*
    class Program {

        [TestMethod()]
        static void Main(string[] args) {
            XElement e = new XElement("Root",
                new XElement("Child",
                    new XAttribute("Att", "1")
                )
            );

            XmlNode xmlNode = e.GetXmlNode();
            Console.WriteLine(xmlNode.OuterXml);

            XElement newElement = xmlNode.GetXElement();
            Console.WriteLine(newElement);
        }
    }
     */

    public enum XElementCreationMethod {
        UseWriter,
        UseConstructor,
        UseParser
    }

} // namespace
